<template>
  <div
    v-if="activeTab"
    class="address-bar position-relative flex-nowrap d-flex justify-center align-center"
  >
    <TabControlBar v-if="isLeft" is-left :tab="activeTab"></TabControlBar>
    <v-defaults-provider
      v-else
      :defaults="{
        VBtn: { size: 'small', color: '', variant: 'text', density: 'comfortable', class: 'ml-1' }
      }"
    >
      <v-btn
        data-testid="webContent-mdiArrowLeft"
        :disabled="!activeTab.nav.canGoBack"
        :icon="mdiArrowLeft"
        @click="tabHandler.back(webContentsId)"
      >
      </v-btn>
      <v-btn
        data-testid="webContent-mdiArrowRight"
        :disabled="!activeTab.nav.canGoForward"
        :icon="mdiArrowRight"
        @click="tabHandler.forward(webContentsId)"
      >
      </v-btn>
      <v-btn
        data-testid="webContent-mdiArrowRefresh"
        :icon="activeTab?.nav.isLoading ? mdiClose : mdiRefresh"
        @click="
          activeTab?.nav.isLoading
            ? tabHandler.stop(webContentsId)
            : tabHandler.refresh(webContentsId)
        "
      />
      <v-btn
        data-testid="webContent-mdiArrowToHome"
        :icon="mdiHomeOutline"
        @click="goToHome"
      ></v-btn>
      <v-btn
        v-if="isActiveLeft"
        data-testid="webContent-mdiArrowmdiExport"
        :icon="activeTab.isInSeparateWindow ? mdiImport : mdiExport"
        @click="toggleSeparateWindow()"
      />
      <v-divider class="ml-2 mr-1" inset vertical />

      <v-btn :icon="mdiStarSettingsOutline" @click="showBookmeak()"></v-btn>

      <v-combobox
        ref="omniboxRef"
        v-model="currentUrl"
        :autofocus="autofocus"
        class="url-input mx-2 cursor-text"
        data-testid="omnibox-input"
        hide-details
        item-title="title"
        item-value="url"
        :items="suggestions"
        :loading="isLoadingSuggestions"
        menu-icon=""
        :menu-props="{
          maxHeight: 400,
          width: menuWidth,
          maxWidth: menuWidth,
          contentClass: 'omnibox-menu'
        }"
        :no-data-text="t('noSuggestionsYet')"
        no-filter
        :placeholder="t('omnibox.placeholder')"
        return-object
        rounded
        spellcheck="false"
        variant="solo"
        @keyup.enter="navigateToUrl"
        @update:menu="onMenuUpdate"
        @update:search="onSearchUpdate"
      >
        <template #item="{ item, props }">
          <v-list-item
            v-bind="props"
            :key="item.raw.id"
            class="chrome-suggestion-item suggestion-item-hover"
            density="default"
            @click="selectSuggestion(item.raw)"
          >
            <template #prepend>
              <v-avatar size="20">
                <v-img v-if="item.raw.favicon" :alt="item.raw.title" cover :src="item.raw.favicon">
                  <template #error>
                    <v-icon
                      class="text-medium-emphasis"
                      :icon="getSuggestionIcon(item.raw)"
                      size="20"
                    />
                  </template>
                </v-img>
                <v-icon
                  v-else
                  class="text-medium-emphasis"
                  :icon="getSuggestionIcon(item.raw)"
                  size="20"
                />
              </v-avatar>
            </template>
            <template #title>
              <span class="text-body-2 text-truncate mt-1">{{ item.raw.title }}</span>
            </template>
            <template #subtitle>
              <div class="text-medium-emphasis text-truncate mb-1">
                {{ item.raw.url }}
              </div>
            </template>
            <template #append>
              <div class="d-flex align-center">
                <v-chip
                  v-if="item.raw.type === 'history' && item.raw.visitCount > 1"
                  class="ms-2 flex-shrink-0"
                  size="x-small"
                  variant="tonal"
                >
                  {{ t('omnibox.times', { count: item.raw.visitCount }) }}
                </v-chip>
                <v-chip
                  v-if="item.raw.type === 'local'"
                  class="ms-2 flex-shrink-0"
                  color="primary"
                  size="x-small"
                  variant="tonal"
                >
                  {{ t('omnibox.local') }}
                </v-chip>
              </div>
              <v-btn
                v-if="item.raw.type === 'history'"
                class="delete-btn ml-2"
                :icon="mdiClose"
                tabindex="-1"
                variant="text"
                @click.stop="deleteHistoryItem(item.raw)"
              />
            </template>
          </v-list-item>
        </template>
        <template #append-inner>
          <save-bookmark-pop v-if="activeTab" :tab="activeTab" />
          <save-pass-pop v-if="activeTab" :tab="activeTab" />
          <TranslateMenu v-if="activeTab" :tab="activeTab" />
        </template>
      </v-combobox>
      <FindInPage style="right: 10px" :tab="activeTab" />
    </v-defaults-provider>
  </div>
</template>

<script lang="ts" setup>
import {
  mdiArrowLeft,
  mdiArrowRight,
  mdiCalendar,
  mdiClose,
  mdiCog,
  mdiEmail,
  mdiExport,
  mdiHistory,
  mdiHome,
  mdiHomeOutline,
  mdiImport,
  mdiMagnify,
  mdiMemory,
  mdiRefresh,
  mdiStarSettingsOutline,
  mdiWeb
} from '@mdi/js'
import FindInPage from '@/components/FindInPage.vue'
import debounce from 'lodash/debounce'
import {
  type ComponentPublicInstance,
  computed,
  nextTick,
  onMounted,
  onUnmounted,
  ref,
  watch
} from 'vue'
import { useI18n } from 'vue-i18n'
import { AddressBarService, type SuggestionItem } from '@/database/addressBarService'
import { useLayoutStore } from '@/windows/layoutBrowser/stores/layout'
import { useSidebarStore } from '@/windows/layoutBrowser/stores/sidebar'
import { useTabStore } from '@/windows/layoutBrowser/stores/tab'
import SaveBookmarkPop from '@/components/bookmark/save-bookmark-pop.vue'

const tabStore = useTabStore()
const sidebarStore = useSidebarStore()
const layoutStore = useLayoutStore()

const tabHandler = _pre_.tab

const activeTab = computed(() => {
  return tabStore.activeTab?.tab
})

const isLeft = computed(() => {
  return sidebarStore.isLeftTab(tabStore.activeTabId)
})

const webContentsId = computed(() => activeTab.value?.webContentsId)

// 响应式数据
const currentUrl = ref<string | null>(activeTab.value?.url || null)
const suggestions = ref<SuggestionItem[]>([])
const isLoadingSuggestions = ref(false)
const searchQuery = ref('')

const omniboxRef = ref<ComponentPublicInstance>()
const menuWidth = ref<number | string>('auto')
let resizeObserver: ResizeObserver | null = null

function updateMenuWidth() {
  nextTick(() => {
    const el = (omniboxRef.value && (omniboxRef.value.$el as HTMLElement)) || null
    if (el) {
      menuWidth.value = el.offsetWidth
    }
  })
}

const isActiveLeft = computed(() => {
  return sidebarStore.isLeftTab(tabStore.activeTabId)
})

// i18n
const { t } = useI18n()

// 监听活动标签页URL变化
watch(
  () => activeTab.value?.url,
  (newUrl, oldUrl) => {
    const url = newUrl ?? ''

    currentUrl.value = url || null
    searchQuery.value = url.trim()

    // 如果URL发生变化，重新生成建议
    if (newUrl !== oldUrl) {
      // 如果地址栏当前有输入内容，重新搜索
      if (searchQuery.value.trim()) {
        debouncedSearch(searchQuery.value)
      } else {
        // 如果没有输入内容，显示最近访问记录（排除当前URL）

        debouncedSearch('')
      }
    }
  }
)

function toggleSeparateWindow() {
  if (!activeTab.value) return
  _pre_.tab.toggleSeparateWindow(activeTab.value.webContentsId)
}

const autofocus = computed(() => {
  const url = currentUrl.value
  return !url || url.trim() === ''
})

// 防抖搜索函数
const debouncedSearch = debounce(async (query: string) => {
  if (!query.trim()) {
    // 空查询时显示最近访问记录
    try {
      isLoadingSuggestions.value = true
      suggestions.value = await AddressBarService.getSearchSuggestions(
        '',
        8,
        currentUrl.value ?? ''
      )
    } catch (error) {
      console.error('获取最近访问记录失败:', error)
      suggestions.value = []
    } finally {
      isLoadingSuggestions.value = false
    }
    return
  }

  try {
    isLoadingSuggestions.value = true
    suggestions.value = await AddressBarService.getSearchSuggestions(
      query,
      8,
      currentUrl.value ?? ''
    )
  } catch (error) {
    console.error('获取搜索建议失败:', error)
    suggestions.value = []
  } finally {
    isLoadingSuggestions.value = false
  }
}, 100)

// 搜索输入更新处理
function onSearchUpdate(query: string | null | undefined) {
  // 类型安全检查：确保 query 是有效的字符串
  const safeQuery = query || ''
  searchQuery.value = safeQuery
  debouncedSearch(safeQuery)
}

// 导航到URL
function navigateToUrl() {
  const url = currentUrl.value

  // 类型安全检查：确保 url 是有效的字符串
  if (!url || !url.trim()) {
    return
  }

  const trimmedUrl = url.trim()
  if (!trimmedUrl) {
    return
  }

  if (!webContentsId.value) return
  // 执行导航
  tabHandler.navigate(trimmedUrl, webContentsId.value)

  // 清空建议列表
  suggestions.value = []
}

// 选择建议项
function selectSuggestion(suggestion: SuggestionItem) {
  if (!suggestion?.url || !webContentsId.value) {
    return
  }
  currentUrl.value = suggestion.url
  tabHandler.navigate(suggestion.url, webContentsId.value)
  suggestions.value = []
}

// 删除历史记录项
async function deleteHistoryItem(suggestion: SuggestionItem) {
  if (suggestion.type !== 'history') {
    return
  }

  try {
    // 从建议项的 id 中提取历史记录的真实 ID
    let historyId: string
    if (suggestion.id.startsWith('history-')) {
      historyId = suggestion.id.replace('history-', '')
    } else if (suggestion.id.startsWith('recent-')) {
      historyId = suggestion.id.replace('recent-', '')
    } else {
      console.error('❌ 无效的建议项 ID 格式:', suggestion.id)
      return
    }

    const recordId = Number.parseInt(historyId, 10)

    if (isNaN(recordId)) {
      console.error('❌ 无效的历史记录 ID:', suggestion.id, '提取的ID:', historyId)
      return
    }

    // 调用删除 API
    const result = await _pre_.browsingHistory.deleteRecord(recordId)

    if (result.success) {
      // 从当前建议列表中移除该项
      suggestions.value = suggestions.value.filter(item => item.id !== suggestion.id)
      console.log('✅ 历史记录删除成功:', suggestion.url)
    } else {
      console.error('❌ 删除历史记录失败:', result.error)
      // 这里可以添加用户友好的错误提示
    }
  } catch (error) {
    console.error('❌ 删除历史记录时发生错误:', error)
    // 这里可以添加用户友好的错误提示
  }
}

// 获取建议项图标
function getSuggestionIcon(suggestion: SuggestionItem): string {
  switch (suggestion.type) {
    case 'history': {
      return mdiHistory
    }
    case 'search': {
      return mdiMagnify
    }
    case 'local': {
      // 根据本地URL的图标名称返回对应的图标
      switch (suggestion.icon) {
        case 'mdiCog': {
          return mdiCog
        }
        case 'mdiHistory': {
          return mdiHistory
        }
        case 'mdiHome': {
          return mdiHome
        }
        case 'mdiCalendar': {
          return mdiCalendar
        }
        case 'mdiEmail': {
          return mdiEmail
        }
        case 'mdiMemory': {
          return mdiMemory
        }
        default: {
          return mdiWeb
        }
      }
    }
    default: {
      return mdiWeb
    }
  }
}

function goToHome() {
  if (!activeTab.value || !webContentsId.value) return
  if (sidebarStore.isLeftTab(activeTab.value.id)) {
    const tab = sidebarStore.findLeftTab(activeTab.value.id)
    if (tab) {
      tabHandler.navigate(tab.origin.url, webContentsId.value)
    }
  } else {
    tabHandler.navigate(void 0, webContentsId.value)
  }
}

function onMenuUpdate(show: boolean) {
  layoutStore.showAddressBarMenu = show
  if (show) updateMenuWidth()
}

function showBookmeak() {
  layoutStore.showBookmarkDrawer = true
}

// 组件挂载时加载初始建议
onMounted(() => {
  debouncedSearch('')
  updateMenuWidth()

  nextTick(() => {
    const el = (omniboxRef.value && (omniboxRef.value.$el as HTMLElement)) || null
    if (!el) return
    resizeObserver = new ResizeObserver(() => {
      menuWidth.value = el.offsetWidth
    })
    resizeObserver.observe(el)
    window.addEventListener('resize', updateMenuWidth)
  })
})

onUnmounted(() => {
  if (resizeObserver) {
    resizeObserver.disconnect()
    resizeObserver = null
  }
  window.removeEventListener('resize', updateMenuWidth)
})
</script>
<style>
.url-input [aria-controls] {
  cursor: text;
}
</style>

<style scoped>
.url-input :deep(.v-field__input) {
  font-weight: 400;
  font-size: 14px;
  min-height: 24px !important;
  padding-top: 2px !important;
  padding-bottom: 0 !important;
}

.address-bar {
  margin-top: 2px;
  padding: 0;
  z-index: 10;
  background: rgb(var(--v-theme-tab-active));
}

:deep(.omnibox-menu) {
  overflow-x: hidden;
}

/* 建议项整体样式优化 */
.suggestion-item-hover {
  /* 确保列表项有足够的右侧间距给删除按钮 */

  :deep(.v-list-item__content) {
    padding-right: 8px;
  }

  /* 优化append区域的布局 */

  :deep(.v-list-item__append) {
    margin-inline-start: 8px !important;
    align-self: center;
  }
}

/* 建议项悬停效果 */
.suggestion-item-hover {
  .delete-btn {
    opacity: 0;
  }

  &:hover .delete-btn {
    opacity: 0.7;
  }

  .delete-btn:hover {
    opacity: 1 !important;
  }
}
</style>
<i18n>
{
  "zhHans": {
    "noSuggestionsYet": "暂无建议",
    "omnibox": {
      "placeholder": "输入网址或搜索内容",
      "local": "本地",
      "times": "{count}次"
    }
  },
  "en": {
    "noSuggestionsYet": "No suggestions yet",
    "omnibox": {
      "placeholder": "Enter URL or search",
      "local": "Local",
      "times": "{count} times"
    }
  }
}
</i18n>
